const express = require("express");
const Book = require("../models/Book");
const Content = require("../models/booksContent")
const router = express.Router();
const Ping = require("../models/PingLun")

//添加书籍
router.post("/add", (req, res) => {
    //console.log(req.body)
    Book.findOne({ bookname: req.body.bookname })
        .then((book) => {
            if (book) {
                return res.status(400).json({ msg: '书名已存在' })
            } else {
                var newBook = new Book({
                    bookname: req.body.bookname,
                    sort: req.body.sort,
                    writername: req.body.writername,
                    writerid:req.body.writerid,
                    explain: req.body.explain
                })
                newBook.save()
                    .then(book => res.json({data:book,status:200}))
                    .catch(err => console.log(err));
            }
    })
})
//根据id删除书籍
router.delete("/delete/:id", (req, res) => {
    Book.findOneAndDelete({ _id: req.params.id })
        .then(
            Content.deleteMany({ bookid: req.params.id })
                .then(Ping.deleteMany({ bookid: req.params.id })
                    .then(res.json({ msg: "成功", status: 200 }))    
            )
    )
        //.catch(err => res.status(404).json(err))
        
})
//根据作者id查询书籍
router.get('/writerbook/:id', (req, res) => {
    // console.log(req.params.id);
    // console.log(req.body.writerid); 
    Book.find({ writerid: req.params.id }, {bookname: 1, state: 1, avatar: 1,isend:1})
        
        .then(book => res.send({ data: book, status: 200 }))
})

// 根据书籍id查询黑名单
router.get('/thisBookHei/:id', (req, res) => {
    Book.findById( req.params.id, { hei:1 })
        .then(book => res.send({ data: book, status: 200 }))
})

//拉黑
router.post(`/addHei/:id`, (req, res) => {
    Book.findByIdAndUpdate(req.params.id, { $addToSet: { hei: req.body.id } })
        .then(res.sendStatus(200))
})

//移出黑名单
router.post(`/pullHei/:id`, (req, res) => {
    Book.findByIdAndUpdate(req.params.id, { $pull: { hei: req.body.id } })
        .then(res.sendStatus(200))
})
//批量移出黑名单
router.post(`/pullManyHei/:id`, (req, res) => {
    Book.findByIdAndUpdate(req.params.id, { $pullAll: { hei: req.body.id } })
        .then(res.sendStatus(200))
})

//根据作者id查询状态正常的书籍 作者详情页
router.get('/thiswriterbooks/:id', (req, res) => {
    // console.log(req.params.id);
    // console.log(req.body.writerid); 
    Book.find({ writerid: req.params.id, state: { $lt: 1 } }, { bookname: 1, state: 1, avatar: 1, explain:1})

        .then(book => res.send({ data: book, status: 200 }))
})
//获得已经审核的书
// router.get("/showBook", (req, res) => {
//     Book.find({ state: { $lt: 2 }}, { bookname: 1,state:1,date:1,sort:1,writerid:1,writername:1})
//         .then(bookname => {
//             if (!bookname) {
//                 return res.json('wu')
//             }
//             res.json({ data: bookname, status: 200 })
//         })

// })
//分页 获得已经审核的书
router.post("/showBook", (req, res) => {
    let a = req.body.pageSize;
    let b = req.body.currentPage
    let c = (b - 1) * a;
    Book.find({ state: { $lt: 2 } }, { bookname: 1, state: 1, date: 1, sort: 1, writerid: 1, writername: 1,isend:1,size:1 }).skip(c).limit(a)
        .then(bookname => {
            Book.find({ state: { $lt: 2 } }).count(true)
                .then(num => res.send({ data: bookname, num: num, status: 200 }))
        })

})


//获得未审核的书 分页
router.post("/shenheBook", (req, res) => {
    let a = req.body.pageSize;
    let b = req.body.currentPage
    let c = (b - 1) * a;
    Book.find({ state: 2 }, { bookname: 1, state: 1, date: 1, sort: 1, writerid: 1, writername: 1 }).skip(c).limit(a)
        .then(bookname => {
            Book.find({ state: 2 }).countDocuments(true)
                .then(num => res.send({ data: bookname, num: num, status: 200 }))
        })

})
//根据书id获取书籍获取全部信息
router.get("/thisbook/:bookid", (req, res) => {
    //console.log(req.params);
    Book.findOne({ _id: req.params.bookid })
        .then(book => {
            if (!book) {
                return res.json('wu')
            }
            res.json({ data: book, status: 200 })
        })
})
//根据书id获取书籍获取部分信息 管理员
router.get("/thisbookA/:bookid", (req, res) => {
    //console.log(req.params);
    Book.findOne({ _id: req.params.bookid }, { bookname: 1, state: 1, date: 1, sort: 1, writerid: 1, writername: 1,isend:1,size:1 })
        .then(book => {
            if (!book) {
                return res.json('wu')
            }
            res.json({ data: book, status: 200 })
        })
})

//模糊搜索书名 管理员
router.get("/thisbookB", (req, res) => {
    let n = req.query.bookname.split('').join(".*");
    let m = new RegExp(n, 'g');
    let a = req.body.pageSize;
    let b = req.body.currentPage
    let c = (b - 1) * a;
    //let name = eval("/" + req.body.bookname + "/i");
    Book.find({ "bookname": m, "state": { $lt: 1 } }, { bookname: 1, state: 1, date: 1, sort: 1, writerid: 1, writername: 1, isend: 1, size: 1 }).skip(c).limit(a)
        .then(books => {
            Book.find({ "bookname": m, "state": { $lt: 1 } }).countDocuments(true)
                .then(num => res.send({ data: books, num: num, status: 200 }))
        })
})

//获取书籍部分信息 作者
router.get("/thisbookW/:bookid", (req, res) => {
    //console.log(req.params);
    Book.findOne({ _id: req.params.bookid },{avatar:1,explain:1,sort:1,date:1,bookname:1})
        .then(book => {
            if (!book) {
                return res.json('wu')
            }
            res.json({ data: book, status: 200 })
        })
})


//读者根据书id获取书籍，获取部分信息
router.get("/readbook/:bookid", (req, res) => {
    //console.log(req.params);
    Book.findOne({ _id: req.params.bookid })
        .then(book => {
            if (!book) {
                return res.json('wu')
            }
            res.json({ data: book, status: 200 })
        })
})
//根据书籍id获取书名
router.get("/thisBookName/:id", (req, res) => {
    Book.findById(req.params.id, { bookname: 1 })
        .then(isname => res.send({data:isname,status:200}))
})
//根据书籍id提交修改信息
router.post('/changeBook/:id', (req, res) => {
    Book.findByIdAndUpdate(req.params.id, { $set: { "bookname": req.body.bookname, "explain": req.body.explain } })
        .then(book => res.send({data:book,status:200}))
})
//更改书籍封面
router.post('/changeBookPic/:id', (req, res) => {
    Book.findByIdAndUpdate(req.params.id, { $set: { "avatar": req.body.url} })
        .then(res.sendStatus(200))
})

//更改作者名
// router.post("/writerName/:id", (req, res) => {
//     Book.update({ writerid: req.params.id }, { $set: { "writername": req.body.name } }, { multi: true })
//         .then(res.sendStatus(200))
// })

//模糊搜索书名
router.get("/searchBook", (req, res) => {
    let n = req.query.bookname.split('').join(".*");
    let m = new RegExp(n, 'g');
    let a = req.body.pageSize;
    let b = req.body.currentPage
    let c = (b - 1) * a;
    //let name = eval("/" + req.body.bookname + "/i");
    Book.find({ "bookname": m, "state": { $lt: 1 } }, { bookname: 1, writername: 1, isend: 1, avatar: 1 }).skip(c).limit(a)
        .then(books => {
            Book.find({ "bookname": m, "state": { $lt: 1 } }).countDocuments(true)
                .then(num => res.send({ data: books, num: num, status: 200 }))
        })
})

// 封禁解封书籍
router.post("/updateState/:id", (req, res) => {
    Book.findByIdAndUpdate(req.params.id, { $set: { "state": req.body.state } })
        .then(res.send({status:200}))
})
//根据分类获取书籍
router.post("/getBookByClass", (req, res) => {
    let a = req.body.pageSize;
    let b = req.body.currentPage
    let c = (b - 1) * a;
    Book.find({ sort: req.body.class, state: 0 }, { avatar: 1, bookname: 1, writerid: 1, writername: 1, isend:1 }).skip(c).limit(a)
        .then(books =>
            Book.find({ sort: req.body.class, state: 0 }).countDocuments(true)
                .then(num => res.send({ data: books,num:num, status: 200 }))
    )
        
})
//字数排序
router.post("/getBookByClassSize", (req, res) => {
    let a = req.body.pageSize;
    let b = req.body.currentPage
    let c = (b - 1) * a;
    Book.find({ sort: req.body.class, state: 0 }, { avatar: 1, bookname: 1, writerid: 1, writername: 1, isend: 1  }).sort({ "size": -1 }).skip(c).limit(a)
        .then(books =>
            Book.find({ sort: req.body.class, state: 0 }).countDocuments(true)
                .then(num => res.send({ data: books, num: num, status: 200 }))
        )

})
//收藏排序
router.post("/getBookByClassShou", (req, res) => {
    let a = req.body.pageSize;
    let b = req.body.currentPage
    let c = (b - 1) * a;
    Book.find({ sort: req.body.class, state: 0 }, { avatar: 1, bookname: 1, writerid: 1, writername: 1, isend: 1  }).sort({ "thiscollection": -1 }).skip(c).limit(a)
        .then(books =>
            Book.find({ sort: req.body.class, state: 0 }).countDocuments(true)
                .then(num => res.send({ data: books, num: num, status: 200 }))
        )
})
//将书籍改为完结状态
router.put(`/changeIsEnd/:id`, (req, res) => {
    Book.findByIdAndUpdate(req.params.id, { $inc: { isend: 1 } })
        .then(res.sendStatus(200))
})

//------------------章节操作----------------------------------
//章节总字数
router.get("/zsize", (req, res) => {
    //console.log(1); .aggregate([{ num: { $sum: "$size" } }])
    let id = '5ff52755450e3d13ecee3af2'
    Content.aggregate([{ $match: { bookid: id } }, { $group: { _id: null, count: { $sum: "$size" } } }])
        .then(w => console.log(w[0].count))
})

//章节字数
router.get("/tsize", (req, res) => {
    let id = "5ff56f7251b6ac164c3266da"
        Content.findById(id, { size:1 })
            .then(w => res.send(w))
})

//创建新章节 id为书籍id
router.post("/addcontent/:id", (req, res) => {
    let con = new Content({ title: req.body.title, bookid: req.params.id })
    con.save()
    .then(con =>res.send({data:con,status:200}))
})
// router.post("/addnew/:id", (req, res) => {
//     // console.log(req.body.newcontent);
//     let newTitle = {}
//     newTitle.title = req.body.title;
//     newTitle.content = '';
//     newTitle.state = 0;
//     Book.findOneAndUpdate(
//         { _id: req.params.id },
//         { $addToSet: { content:newTitle } },
//         { new: true }
//     ).then(book => res.json({
//         data: book,
//         status: 200
//     })).catch(err => console.log(err));
// })

//根据书籍id获取章节名(分页版)
router.post("/gettitlePage/:id", (req, res) => {
    let a = req.body.pageSize;
    let b = req.body.currentPage
    let c = (b - 1) * a;
    // console.log(a);
    // console.log(b);
    Content.find({ bookid: req.params.id }, { title: 1, state: 1, date: 1 }).skip(c).limit(a)
        .then(con => 
            Content.find({ bookid: req.params.id }, { title: 1, state: 1, date: 1 }).count(true)
                .then(num => res.send({data:con,num:num,status:200}))
    )
        //.then(con => res.send({data:con}))
})
//根据根据书籍id获取章节名(不分页)
router.get("/gettitle/:id", (req, res) => {
    Content.find({ bookid: req.params.id}, { title: 1, state: 1, date: 1 })
        .then(con => res.send({data:con,status:200}))
})
//根据根据书籍id获取章节名(不分页)限制状态
router.get("/readTitle/:id", (req, res) => {
    Content.find({ bookid: req.params.id, state: 0 }, { title: 1, state: 1, date: 1 })
        .then(con => res.send({ data: con, status: 200 }))
})

//读者读书，限制章节状态
router.get("/userReadBook/:id", (req, res) => {
    Content.find({ bookid: req.params.id,"state":0 }, { title: 1, state: 1, date: 1 })
        .then(con => res.send({ data: con, status: 200 }))
})
//聚合查询
// router.get("/gettitle/:id", (req, res) => {
//     Content.aggregate([{ $group: { _id: "$bookid", num: { $sum: 1}} }])
//         .then(con => console.log(con))
//         // .then(con => res.send({ data: con }))
// })
//根据章节id获取章节内容
router.get('/getcontent/:id', (req, res) => {
    Content.findById(req.params.id, { content: 1 })
        .then(content => res.send({data:content,status:200}))
})

//根据章节id提交内容修改并更改书籍总字数
// router.post("/upcontent/:id", (req, res) => {
//     Content.findByIdAndUpdate(req.params.id, { $set: { 'content': req.body.content,'size':req.body.size } })
//         .then(content => res.send({data:content,status:200}))
// })
router.post("/upcontent/:id", (req, res) => {
    Content.findByIdAndUpdate(req.params.id, { $set: { 'content': req.body.content, 'size': req.body.size } })
        .then( con =>
            Content.aggregate([{ $match: { bookid: con.bookid } }, { $group: { _id: null, count: { $sum: "$size" } } }])
                .then(num =>
                    Book.findByIdAndUpdate(con.bookid, { $set: { size: num[0].count } })
                        .then(res.send({ status: 200 }))
            )
    )
})


//根据章节id删除章节
router.delete("/deleteTitle/:id", (req, res) => {
    Content.findByIdAndDelete(req.params.id)
        .then(res.sendStatus(200))
})
//根据章节id更改章节名
router.post('/changeTitleName/:id', (req, res) => {
    Content.findByIdAndUpdate(req.params.id, { $set: { 'title': req.body.title } })
        .then(res.sendStatus(200))
})
// 封禁解封章节
router.post("/updateTitleState/:id", (req, res) => {
    Content.findByIdAndUpdate(req.params.id, { $set: { "state": req.body.state } })
        .then(res.send({ status: 200 }))
})


module.exports = router;